package com.faceidentify

import android.os.Handler
import android.os.Looper
import android.util.Log
import com.google.gson.JsonObject
import com.google.gson.JsonParser
import okhttp3.*
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody.Companion.toRequestBody
import java.io.IOException

class HttpHelper {

    companion object {
        var client: OkHttpClient? = null
        var handler: Handler? = null
        var httpHelper: HttpHelper? = null


        fun getInstance(): HttpHelper? {
            if (httpHelper == null) {
                httpHelper = HttpHelper()
            }
            return httpHelper
        }
    }


    constructor() {
        client = OkHttpClient()
        handler = Handler(Looper.myLooper()!!)
    }


    fun postJsonObject(url: String?, jsonObject: JsonObject?, listener: ResponseListener) {
        var builder = Request.Builder()
                .url(url!!)
                .post(jsonObject.toString().toRequestBody("application/json".toMediaType()))

        val request: Request = builder.build()
        val call = client?.newCall(request)
        call?.enqueue(object : Callback {
            override fun onFailure(call: Call, e: IOException) {
                Log.e("错误", e.message.toString())
            }

            @Throws(IOException::class)
            override fun onResponse(call: Call, response: Response) {
                val jsonObject = JsonParser().parse(response.body!!.string()).asJsonObject
                handler!!.post { listener.doAction(jsonObject) }
            }
        })
    }
}